﻿using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;

namespace YanZhiwei.DotNet3._5.Utilities.Common
{
    /// <summary>
    /// Json 帮助类
    /// </summary>
    public static class JsonHelper
    {
        #region 将DataTable转换成JSON
        /// <summary>
        /// 将DataTable转换成JSON
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>JSON</returns>
        public static string ToJson(this DataTable dt)
        {
            JavaScriptSerializer _serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> _rows =
              new List<Dictionary<string, object>>();
            Dictionary<string, object> _row = null;
            foreach (DataRow dr in dt.Rows)
            {
                _row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    _row.Add(col.ColumnName.Trim(), dr[col]);
                }
                _rows.Add(_row);
            }
            return _serializer.Serialize(_rows);
        }
        #endregion 
    }
}
